package day06;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zouran
 * createDate：2024/6/29  16:36
 */
class MyAccount {
    private int balance;

    public MyAccount(int balance) {
        this.balance = balance;
    }

    public synchronized void store(int money) throws InterruptedException {
        balance += money;
        System.out.printf("%s:存入%d,当前余额%d\n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), money, balance);
        this.notify();
    }

    public synchronized void take(int money) throws InterruptedException {
        while (true) {
            if (money <= balance) {
                balance -= money;
                System.out.printf("%s:取出%d,当前余额%d\n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), money, balance);
                this.notify();
                break;
            } else {
                System.out.printf("%s:余额不足!,预支:%d,剩余%d\n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), money, balance);
                this.wait();
            }
        }
    }
}

public class MultipleThread {
    public static void main(String[] args) {
        MyAccount account = new MyAccount(0);
        for (int i = 1; i <= 3; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    account.store(finalI * 100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
            new Thread(() -> {
                try {
                    account.take(finalI * 100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
        }
    }
}
